package com.wxy.demo.util;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.wxy.demo.entity.DataSourceInfo;
import com.wxy.demo.enums.DatasourceTypeEnum;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/1/15 13:31
 */
public class DbUtils {

    private final static TimedCache<Long, HikariDataSource> DATA_SOURCE_CACHE;

    static {
        DATA_SOURCE_CACHE = CacheUtil.newTimedCache(TimeUnit.DAYS.toMillis(1));
        DATA_SOURCE_CACHE.setListener((id, ds) -> ds.close());
        DATA_SOURCE_CACHE.schedulePrune(TimeUnit.HOURS.toMillis(1));
    }

    public static Connection getConn(DataSourceInfo dataSourceInfo) throws SQLException, ClassNotFoundException {
        if (dataSourceInfo.getId() == null) {
            Class.forName(DatasourceTypeEnum.valueOf(dataSourceInfo.getType().toUpperCase())
                    .getDriverClassName());
            return DriverManager.getConnection(buildUrl(dataSourceInfo), dataSourceInfo.getUsername(), dataSourceInfo.getPassword());
        } else {
            HikariDataSource hds = DATA_SOURCE_CACHE.get(dataSourceInfo.getId());
            if (hds == null) {
                HikariConfig config = new HikariConfig();
                config.setJdbcUrl(buildUrl(dataSourceInfo));
                config.setUsername(dataSourceInfo.getUsername());
                config.setPassword(dataSourceInfo.getPassword());
                config.setPoolName("hikari-" + dataSourceInfo.getId());
                config.setConnectionTimeout(10000);
                config.setIdleTimeout(30000);
                config.setMaxLifetime(300000);
                config.setMaximumPoolSize(60);
                config.setMinimumIdle(10);
                hds = new HikariDataSource(config);
                DATA_SOURCE_CACHE.put(dataSourceInfo.getId(), hds);
            }
            return hds.getConnection();
        }
    }

    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {

            }
        }
    }

    public static List<Map<String, Object>> query(Connection conn, String sql, Object[] param) throws SQLException {
        PreparedStatement ps = conn.prepareStatement(sql);
        if (param != null && param.length > 0) {
            for (int i = 0; i < param.length; i++) {
                ps.setObject(i + 1, param[i]);
            }
        }
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData md = rs.getMetaData();
        int num = md.getColumnCount();
        List<Map<String, Object>> listOfRows = new ArrayList<>();
        while (rs.next()) {
            Map<String, Object> mapOfCols = new HashMap<>(num);
            for (int i = 1; i <= num; i++) {
                mapOfCols.put(md.getColumnName(i), rs.getObject(i));
            }
            listOfRows.add(mapOfCols);
        }
        return listOfRows;
    }

    private static String buildUrl(DataSourceInfo dataSourceInfo) {
        String urlFormat = DatasourceTypeEnum.valueOf(dataSourceInfo.getType().toUpperCase()).getUrlFormat();
        return String.format(urlFormat, dataSourceInfo.getHost(), dataSourceInfo.getPort(), dataSourceInfo.getDbname());
    }
}
